package cc.android.testapp.ui;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import cc.android.testapp.R;
import cc.android.testapp.cfg.Config;
import cc.android.testapp.ui.inject.InjectView;
import cc.android.testapp.ui.inject.ViewInject;
import cc.android.testapp.ui.part.CNumbEdit;
import cc.android.testapp.util.CLog;
import cc.android.testapp.util.RenameYouhua;
import cc.commons.util.CollUtil;
import cc.commons.util.FileUtil;

public class BoxNameDialog extends AlertDialog implements View.OnClickListener {
    private static HashMap<File, File> mHistroyImg = null;
    private HashMap<File, String> mImgs;
    private MainActivity mAct;
    @InjectView(id = R.id.et_dir_name)
    private EditText mFileName;
    @InjectView(id = R.id.et_yh)
    private EditText mYH;
    @InjectView(id = R.id.et_filename_extra)
    private EditText mExtra;
    private String mOriginExtra = null;

    public BoxNameDialog(MainActivity context, HashMap<File, String> pImgs) {
        super(context);

        this.mAct = context;
        this.mImgs = pImgs;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        View tView = this.getLayoutInflater().inflate(R.layout.box_img_rename, null);
        this.setContentView(tView);

        ViewInject.injectView(this, this::findViewById, null);
        this.findViewById(R.id.btn_et_apply).setOnClickListener(this);
        this.findViewById(R.id.btn_et_cancel).setOnClickListener(this);

        // 初始化输入框内容
        ClipboardManager tMan = (ClipboardManager) this.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData tCData = tMan.getPrimaryClip();
        if (tCData != null && tCData.getItemCount() > 0) {
            for (int i = 0; i < 2 && i < tCData.getItemCount(); i++) {
                String tText = tCData.getItemAt(i).getText().toString();
                if (tText.startsWith("YH-")) this.mYH.setText(tText);
                if (tText.contains("GF")) this.mFileName.setText(tText);
            }
        }
        String tStr = Config.getConfig().optString("filename_extra");
        if (!TextUtils.isEmpty(tStr)) this.mExtra.setText(tStr);
        this.mOriginExtra = tStr;
    }

    @Override
    public void onClick(View pView) {
        if (pView.getId() == R.id.btn_et_apply) {
            String tName = this.mFileName.getText().toString().trim();
            if (tName.isEmpty()) {
                Toast.makeText(this.mAct, "请输入文件名", Toast.LENGTH_SHORT).show();
                return;
            }
            tName += "换盒";

            for (int sId : new int[]{R.id.cnumb_xinShu, R.id.cnumb_2scsc, R.id.cnumb_1_4fgq, R.id.cnumb_1_8fgq}) {
                CNumbEdit tCNE = this.findViewById(sId);
                tName += tCNE.getFormatStr();
            }
            String tExtra = this.mExtra.getText().toString();
            if (!TextUtils.isEmpty(tExtra)) tName += tExtra;
            if (!Objects.equals(tExtra, this.mOriginExtra)) {
                try {
                    Config.getConfig().put("filename_extra", tExtra);
                    Config.saveConfig();
                } catch (JSONException ignored) {
                }
            }
            tName = tName.replace(":", "：");

            File tDir = new File(Environment.getExternalStorageDirectory(), "Download/按需暂存/更换分线盒/临时/");
            File[] tDirs = tDir.listFiles((file) -> file.isDirectory() && CollUtil.isEmpty(file.list()));
            File tDirTarget = new File(tDir, new SimpleDateFormat("yyMMdd").format(new Date()) + '-' + tName);
            if (CollUtil.isNotEmpty(tDirs)) {
                for (File sDir : tDirs) {
                    if (sDir.renameTo(tDirTarget)) break;
                }
            }
            if (!tDirTarget.isDirectory()) {
                if (!tDirTarget.mkdir()) {
                    Toast.makeText(this.mAct, "无法创建文件夹: " + tDirTarget.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            // 开始改名字
            HashMap<File, File> tRenamed = new HashMap<>();
            for (Map.Entry<File, String> sEntry : mImgs.entrySet()) {
                File tTarget = new File(tDirTarget, sEntry.getValue());
                if (sEntry.getKey().renameTo(tTarget)) {
                    tRenamed.put(tTarget, sEntry.getKey());
                } else {
                    Toast.makeText(this.mAct, "无法移动文件(" + sEntry.getKey().getAbsolutePath() + ")至("
                            + tTarget.getName() + ")", Toast.LENGTH_SHORT).show();
                    renameFile(tRenamed);
                    return;
                }
            }

            String tStr = this.mYH.getText().toString().trim();
            File tYH = null;
            if (!tStr.isEmpty()) {
                try {
                    tYH = new File(tDirTarget, tStr);
                    tYH.createNewFile();
                } catch (IOException ignored) {
                    CLog.log("隐患单创建失败");
                    tYH = null;
                }
            }

            mHistroyImg = tRenamed;
            mHistroyImg.put(tYH, null);
            this.dismiss();
            Toast.makeText(this.mAct, "已经归档至: " + tDirTarget.getName(), Toast.LENGTH_SHORT).show();

        } else if (pView.getId() == R.id.btn_et_cancel) this.dismiss();
    }

    public static boolean renameFile(HashMap<File, File> pFiles) {
        boolean tResult = true;
        for (Map.Entry<File, File> sEntry : pFiles.entrySet()) {
            File tTo = sEntry.getValue();
            if (tTo != null) tResult &= sEntry.getKey().renameTo(sEntry.getValue());
            else FileUtil.deleteFile(sEntry.getKey());
        }
        return tResult;
    }

    @Override
    public void show() {
        super.show();
        Window window = getWindow();
        if (window != null) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        }
    }

    public static void handleRestore(MainActivity pAct) {
        if (mHistroyImg == null) {
            Toast.makeText(pAct, "无历史记录可以恢复", Toast.LENGTH_SHORT).show();
        } else {
            if (renameFile(mHistroyImg)) {
                Toast.makeText(pAct, "已经恢复", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(pAct, "未能完全恢复文件", Toast.LENGTH_SHORT).show();
            }
            mHistroyImg = null;
        }
    }

}
